<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>用户名验证</title>
  <style>
    span {
      color: #aaa;
      font-size: 14px;
    }

    .right {
      color: green;
    }

    .wrong {
      color: red;
    }
  </style>
</head>
<body>
  <input type="text" class="uname"> <span>请输入用户名</span>
  <script>
    //  量词是设定某个模式出现的次数
    var reg = /^[a-zA-Z0-9_-]{6,16}$/ // 这个模式用户只能输入英文字母 数字 下划线 短横线但是有边界符和[] 这就限定了只能多选1
    // {6,16}  中间不要有空格
    // console.log(reg.test('a'));
    // console.log(reg.test('8'));
    // console.log(reg.test('18'));
    // console.log(reg.test('aa'));
    // console.log('-------------');
    // console.log(reg.test('andy-red'));
    // console.log(reg.test('andy_red'));
    // console.log(reg.test('andy007'));
    // console.log(reg.test('andy!007'));
    var uname = document.querySelector('.uname')
    var span = document.querySelector('span')
    uname.onblur = function () {
      if (reg.test(this.value)) {
        console.log('正确的')
        span.className = 'right'
        span.innerHTML = '用户名格式输入正确'
      } else {
        console.log('错误的')
        span.className = 'wrong'
        span.innerHTML = '用户名格式输入不正确'
      }
    }
  </script>
</body>
</html>